      1  import java.io.InputStream;

      2  import java.io.OutputStream;

      3  import java.io.IOException;

      4

      5  /**

      6     This class encrypts files using the Caesar cipher.

      7     For decryption, use an encryptor whose key is the

      8     negative of the encryption key.

      9  */

     10  public class CaesarCipher

     11  {

     12     private int key;

     13

     14     /**

     15        Constructs a cipher object with a given key.

     16        @param aKey the encryption key

     17     */

     18     public CaesarCipher(int aKey)

     19     {

     20        key = aKey;

     21     }

     22

     23     /**

     24        Encrypts the contents of a stream.

     25        @param in the input stream

     26        @param out the output stream

     27     */

     28     public void encryptStream(InputStream in, OutputStream out)

     29           throws IOException

     30     {

     31        boolean done = false;

     32        while (!done)

     33        {

     34           int next = in.read();

     35           if (next == -1)

     36           {

     37              done = true;

     38           }

     39           else

     40           {

     41              int encrypted = encrypt(next);

     42              out.write(encrypted);

     43           }

     44        }

     45     }

     46

     47     /**

     48        Encrypts a value.

     49        @param b the value to encrypt (between 0 and 255)

     50        @return the encrypted value

     51     */

     52     public int encrypt(int b)

     53     {

     54        return (b + key) % 256;

     55     }

     56  }